package com.jojo.bubble.controller.api;

import com.jojo.bubble.common.domain.AjaxResult;
import com.jojo.bubble.common.pages.PageUtil;
import com.jojo.bubble.entity.*;
import com.jojo.bubble.service.*;
import org.apache.ibatis.annotations.Param;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author JoJo
 * @Date 2023/8/10 5:52
 * @Description
 * @Version 1.0
 */
@RestController
@RequestMapping("/api/agent")
public class AgentApiController {
    @Resource
    private AgentService agentService;
    @Resource
    private ShopService shopService;

    @Resource
    private DevService devService;
    @Resource
    private OrderService orderService;
    @Resource
    BalanceService balanceService;
    @Resource
    UserService userService;

    @RequestMapping("/login")
    public AjaxResult agentLogin(Agent agent) {
        Agent record = agentService.queryByPhone(agent.getPhone());
        if (ObjectUtils.isEmpty(record)) {
            return AjaxResult.error("账号不存在");
        }
        if (record.getStatus() != 2) {
            return AjaxResult.error("账号审核中");
        }
        if (agent.getPassword().equals(record.getPassword())) {
            return AjaxResult.success(record);
        } else {
            return AjaxResult.error("密码错误");
        }
    }

    @PostMapping("/insert")
    public AjaxResult newAgent(Agent agent) {
        Agent record = agentService.queryByPhone(agent.getPhone());
        if (!ObjectUtils.isEmpty(record)) {
            return AjaxResult.error("手机号已注册");
        }
        if(agent.getLevel()==1 && agent.getPercent().compareTo(new BigDecimal("0.994"))==1){
            return AjaxResult.error("分成比例不能大于0.994");
        }
        agentService.insert(agent);

        return AjaxResult.success();
    }

    @PostMapping("/update")
    public AjaxResult update(Agent agent) {
        Agent record = agentService.queryByPhone(agent.getPhone());
        if (!ObjectUtils.isEmpty(record) && !Objects.equals(record.getId(), agent.getId())) {
            return AjaxResult.error("手机号已注册");
        }
        agentService.update(agent);
        return AjaxResult.success();
    }

    @GetMapping("/check")
    public AjaxResult checkAgent(Agent agent) {
        Agent recode = agentService.queryByUser(agent.getAgentId());
        if (ObjectUtils.isEmpty(recode)) {
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }

    @GetMapping("/balanceList")
    public AjaxResult agentBalance(Balance record) {
        List<Balance> balanceList = balanceService.getList(record);
        return AjaxResult.success(balanceList);
    }

    @PostMapping("/balance/insert")
    public AjaxResult newBalance(Balance record) {

        Agent agent = agentService.getInfo(record.getAgentId());
        if (ObjectUtils.isEmpty(agent)) {
            return AjaxResult.error();
        }
        agent.setBalance(agent.getBalance().subtract(record.getMoney()));
        agentService.update(agent);
        balanceService.insert(record);
        return AjaxResult.success();
    }

    @GetMapping("/count")
    public AjaxResult count(Agent record) throws ParseException {
        AgentVo agentVo = new AgentVo();
        Agent agent = agentService.getInfo(record.getId());

        if (!ObjectUtils.isEmpty(agent)) {
            agentVo.setAgent(agent);
            Order order = new Order();
            order.setAgentId(agent.getId());
            order.setStatus(1);
            if (StringUtils.hasLength(record.getData1()) || StringUtils.hasLength(record.getData2())) {

                if(StringUtils.hasLength(record.getData1())) {
                    Date startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(record.getData1());
                    order.setStartTime(startTime);
                }
                if(StringUtils.hasLength(record.getData2())) {
                    Date endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(record.getData2());
                    order.setEndTime(endTime);
                }
                List<Order> orderList = orderService.getList(order);
                BigDecimal orderPrice = BigDecimal.ZERO;
                for (Order order1 : orderList) {
                    orderPrice = orderPrice.add(order1.getMoney());
                }
                agentVo.setBalance(orderPrice);
                agentVo.setOrderNum(orderList.size());
            } else {
                int orderNum = orderService.count(order);
                agentVo.setOrderNum(orderNum);
                agentVo.setBalance(agent.getBalance());


            }
            Shop shop = new Shop();
            shop.setAgentId(agent.getId());
            Dev dev = new Dev();
            dev.setAgentId(agent.getId());

            int shopNum = shopService.count(shop);
            int devNum = devService.count(dev);
            agentVo.setShopNum(shopNum);
            agentVo.setDevNum(devNum);
            agentVo.setToday(new Date());
            Calendar calendar1 = Calendar.getInstance();
            calendar1.set(Calendar.HOUR_OF_DAY, 0);
            calendar1.set(Calendar.MINUTE, 0);
            calendar1.set(Calendar.SECOND, 0);
            calendar1.set(Calendar.MILLISECOND, 0);
            Date startOfDay = calendar1.getTime();
            Order order1 = new Order();
            // 获取当日的24点（即第二天的0点）
            calendar1.add(Calendar.DAY_OF_MONTH, 1);
            Date endOfDay = calendar1.getTime();
            order1.setStartTime(startOfDay);
            order1.setEndTime(endOfDay);
            order1.setAgentId(record.getId());
            order1.setStatus(1);
            List<Order> todayOrders = orderService.getList(order1);
            BigDecimal todayPrice = BigDecimal.ZERO;
            for (Order order2 : todayOrders) {
                todayPrice = todayPrice.add(order2.getMoney());
            }
            agentVo.setTodayBalance(todayPrice);
            agentVo.setTodayOrderNum(todayOrders.size());
        }

        return AjaxResult.success(agentVo);
    }

    @GetMapping("/shopList")
    public AjaxResult shopList(Agent agent) {
        List<Agent> agentList = agentService.getList(agent);
        return AjaxResult.success(agentList);
    }

    @GetMapping("/aMerchantList")
    public AjaxResult aMerchantList(Agent agent,@RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum,@RequestParam(defaultValue = "10",value = "pageSize") Integer pageSize) {
        Pageable pageable = PageRequest.of(pageNum-1,pageSize);
        List<Agent> agentList = agentService.queryAllByLimit(agent,pageable);
        int all = agentService.count(agent);
        PageUtil page = new PageUtil(agentList,all,pageSize,pageNum);
        return AjaxResult.success(page);
    }

    @GetMapping("/dev/list")
    public AjaxResult devList(Dev dev,@RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum,@RequestParam(defaultValue = "10",value = "pageSize") Integer pageSize) {
//        Agent record = agentService.getInfo(agentId);
//        Dev dev = new Dev();
//        dev.setAgentId(agentId);
        Pageable pageable = PageRequest.of(pageNum-1,pageSize);
        List<Dev> devList = devService.queryAllByLimit(dev,pageable);
        int all = devService.count(dev);
        PageUtil page = new PageUtil(devList,all,pageSize,pageNum);
        return AjaxResult.success(page);
    }

    @GetMapping("/dev/info")
    public AjaxResult devInfo(Dev dev) {
        Dev record = devService.getInfo(dev.getId());
        return AjaxResult.success(record);
    }

    @PostMapping("/dev/update")
    public AjaxResult devUpdate(Dev dev) {
        Dev record = devService.queryByCode(dev.getCode());
        if (ObjectUtils.isEmpty(record)) {
            return AjaxResult.error("设备码错误");
        }
        if (!record.getAgentId().equals(dev.getAgentId()) && record.getAgentId() != 0 && dev.getAgentId() != 0) {
            return AjaxResult.error("设备已被绑定");
        }
        if (dev.getAgentId() == 0) {
            record.setAddress("");
            record.setAgentId(dev.getAgentId());
            record.setLat(new BigDecimal(0));
            record.setLng(new BigDecimal(0));
        } else {
            record.setAddress(dev.getAddress());
            record.setAgentId(dev.getAgentId());
            record.setLat(dev.getLat());
            record.setLng(dev.getLng());
        }
        devService.update(record);
        return AjaxResult.success();
    }
}
